package org.darcy.service.privilege.impl;

import static org.darcy.framework.constant.SysConstant.LOGIN_USER;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.darcy.dao.privilege.SysUserMapper;
import org.darcy.entity.org.Staff;
import org.darcy.entity.privilege.SysRole;
import org.darcy.entity.privilege.SysUser;
import org.darcy.entity.privilege.SysUserRole;
import org.darcy.entity.sys.SysFile;
import org.darcy.framework.constant.SysConstant;
import org.darcy.framework.exception.BusinessException;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.framework.model.PageData;
import org.darcy.framework.model.PageParam;
import org.darcy.framework.model.R;
import org.darcy.service.org.StaffService;
import org.darcy.service.privilege.SysRoleService;
import org.darcy.service.privilege.SysUserRoleService;
import org.darcy.service.privilege.SysUserService;
import org.darcy.service.sys.SysFileService;
import org.darcy.service.sys.UploadService;
import org.darcy.utils.common.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;

@Service
public class SysUserServiceImpl extends GenericServiceImpl<SysUser> implements SysUserService {

	@Autowired
	private SysUserMapper SysUserMapper;

	@Lazy
	@Autowired
	private SysUserRoleService SysUserRoleService;

	@Lazy
	@Autowired
	private SysRoleService SysRoleService;

	@Lazy
	@Autowired
	private StaffService StaffService;

	@Lazy
	@Autowired
	private UploadService UploadService;
	
	@Lazy
	@Autowired
	private SysFileService SysFileService;

	@Override
	public SysUser getUser(String username) {
		if (StringUtils.isBlank(username)) {
			return null;
		}
		LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
		userLambdaQueryWrapper.eq(SysUser::getUsername, username).or().eq(SysUser::getMobile, username);
		List<SysUser> list = this.getList(userLambdaQueryWrapper);
		if (CollectionUtils.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public R login(String username, String password) {
		LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
		userLambdaQueryWrapper.eq(SysUser::getPassword, this.getMd5Password(password))
				.and(obj -> obj.eq(SysUser::getUsername, username.trim()).or().eq(SysUser::getMobile, username.trim()));
		List<SysUser> list = this.getList(userLambdaQueryWrapper);
		if (CollectionUtils.isEmpty(list)) {
			return R.error("账号或密码不正确!");
		}
		SysUser user = list.get(0);
		if(user.getImage()!=null) {
			user.setImageUrl(SysFileService.getById(user.getImage()).getUrl());			
		}
		StpUtil.login(user.getId());
		SaSession session = StpUtil.getSessionByLoginId(user.getId());
		session.set(LOGIN_USER, user);
		List<SysRole> roles = SysRoleService.getListByUserId(user.getId());
		session.set(SysConstant.LOGIN_ROLE_LIST, roles);
		SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
		String tokenValue = tokenInfo.getTokenValue();
		return R.ok("登录成功").data(tokenValue);
	}

	@Override
	public PageData<SysUser> page(PageParam<SysUser> param) {
		IPage<SysUser> queryPage = new Page<>(param.getQuery().getPageNum(), param.getQuery().getPageSize());
		IPage<SysUser> page = SysUserMapper.getPage(queryPage, param.getEntity());
		PageData<SysUser> pageData = new PageData<SysUser>(page, param);
		return pageData;
	}

	@Override
	public List<SysUser> getAll(SysUser user) {
		QueryWrapper<SysUser> params = new QueryWrapper<>(user);
		return this.getList(params);
	}

	@Override
	public void setPassword(SysUser user) {
		user.setPassword(this.getMd5Password(user.getPassword()));
		this.update(user);
	}

	private String getMd5Password(String password) {
		if (StringUtils.isNotBlank(password)) {
			return MD5Util.getMD5String(SysConstant.MD5_PREFIX + password.trim());
		} else {
			throw new BusinessException("password不能为空");
		}
	}

	@Override
	public Map<Integer, String> getNameMapByIds(List<Integer> userIds) {
		Map<Integer, String> map = this.getByIds(userIds).stream()
				.collect(Collectors.toMap(SysUser::getId, SysUser::getRealName));
		return map;
	}

	@Override
	public SysUser addUser(Staff staff) {
		// 先查找
		SysUser existUser = this.getUser(staff.getName());
		if (existUser != null) {
			return existUser;
		}
		SysUser user = new SysUser();
		user.setRealName(staff.getName());
		user.setUsername(staff.getName());
		user.setPassword(getMd5Password("111111")); // 默认密码
		this.insert(user);
		// 用户角色
		SysUserRole userRole = new SysUserRole();
		userRole.setUserId(user.getId());
		userRole.setRoleId(2);// 默认角色:2 普通用户
		SysUserRoleService.insert(userRole);
		return user;

	}

	@Override
	public SysUser update(SysUser data) {
		if (data.getImageBase64Content() != null) {
			SysFile file = UploadService.upload(data.getImageBase64Content());
			data.setImage(file.getId());
		}
		return super.update(data);
	}
}
